package edu.sdjzu.exam.controller;



import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;

import edu.sdjzu.exam.dto.cheat.EnvironmentLogDTO;
import edu.sdjzu.exam.dto.examSession.*;
import edu.sdjzu.exam.service.examSession.ExamSessionService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import edu.sdjzu.exam.common.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/exam-sessions")
@RequiredArgsConstructor
@SaCheckLogin
public class ExamSessionController {

    private final ExamSessionService examSessionService;

    @PostMapping("/start")
    @SaCheckRole("student")
    public CommonResponse<Long> startExam(@Valid @RequestBody StartExamDTO startDTO) {
        try {
            Long sessionId = examSessionService.startExam(startDTO);
            return CommonResponse.success("考试开始成功", sessionId);
        } catch (Exception e) {
            return CommonResponse.error("开始考试失败：" + e.getMessage());
        }
    }

    @PostMapping("/save-draft")
    @SaCheckRole("student")
    public CommonResponse<String> saveDraft(@Valid @RequestBody SaveDraftDTO draftDTO) {
        try {
            examSessionService.saveDraft(draftDTO);
            return CommonResponse.success("草稿保存成功");
        } catch (Exception e) {
            return CommonResponse.error("保存草稿失败：" + e.getMessage());
        }
    }

    @PostMapping("/submit")
    @SaCheckRole("student")
    public CommonResponse<String> submitExam(@Valid @RequestBody SubmitExamDTO submitDTO) {
        try {
            examSessionService.submitExam(submitDTO);
            return CommonResponse.success("考试提交成功");
        } catch (Exception e) {
            return CommonResponse.error("提交考试失败：" + e.getMessage());
        }
    }

    @PostMapping("/resume")
    @SaCheckRole("student")
    public CommonResponse<ExamSessionDTO> resumeExam(@Valid @RequestBody ResumeExamDTO resumeDTO) {
        try {
            ExamSessionDTO sessionDTO = examSessionService.resumeExam(resumeDTO);
            return CommonResponse.success("恢复考试成功", sessionDTO);
        } catch (Exception e) {
            return CommonResponse.error("恢复考试失败：" + e.getMessage());
        }
    }

    @PostMapping("/get")
    @SaCheckRole("student")
    public CommonResponse<ExamSessionDTO> getExamSession(@Valid @RequestBody SessionIdDTO sessionIdDTO) {
        try {
            ExamSessionDTO sessionDTO = examSessionService.getExamSession(sessionIdDTO.getSessionId());
            return CommonResponse.success(sessionDTO);
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResponse.error("获取考试会话失败：" + e.getMessage());
        }
    }

    @PostMapping("/monitor")
    @SaCheckRole("teacher")
    public CommonResponse<List<ExamSessionDTO>> monitorExamSessions(@Valid @RequestBody ExamIdDTO examIdDTO) {
        try {
            List<ExamSessionDTO> sessions = examSessionService.monitorExamSessions(examIdDTO.getExamId());
            return CommonResponse.success(sessions);
        } catch (Exception e) {
            return CommonResponse.error("监控考试会话失败：" + e.getMessage());
        }
    }

    @GetMapping("/list")
    @SaCheckRole("student")
    public CommonResponse<List<ExamSessionDTO>> getStudentExamSessions(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer size,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) Long examId) {
        try {
            StudentExamRecordsDTO requestDTO = new StudentExamRecordsDTO();
            requestDTO.setPage(page);
            requestDTO.setSize(size);
            requestDTO.setStatus(status);
            requestDTO.setExamId(examId);
            
            List<ExamSessionDTO> sessions = examSessionService.getStudentExamSessions(requestDTO);
            return CommonResponse.success(sessions);
        } catch (Exception e) {
            return CommonResponse.error("获取学生考试会话失败：" + e.getMessage());
        }
    }

    @PostMapping("/log-environment")
    @SaCheckRole("student")
    public CommonResponse<String> logEnvironment(@Valid @RequestBody EnvironmentLogDTO envLogDTO) {
        try {
            examSessionService.logEnvironment(envLogDTO);
            return CommonResponse.success("环境日志记录成功");
        } catch (Exception e) {
            return CommonResponse.error("记录环境日志失败：" + e.getMessage());
        }
    }
    
    @GetMapping("/get-by-exam-student")
    @SaCheckRole("student")
    public CommonResponse<ExamSessionDTO> getExamSessionByExamAndStudent(
            @RequestParam @NotNull(message = "试卷ID不能为空") Long examId) {
        try {
            Long studentId = cn.dev33.satoken.stp.StpUtil.getLoginIdAsLong();
            ExamSessionDTO sessionDTO = examSessionService.getExamSessionByExamAndStudent(examId, studentId);
            if (sessionDTO == null) {
                return CommonResponse.success("考试会话不存在", null);
            }
            return CommonResponse.success(sessionDTO);
        } catch (Exception e) {
            log.error(e.getMessage()+"112");
            return null;
        }
    }

    @Data
    public static class SessionIdDTO {
        @NotNull(message = "考试会话ID不能为空")
        private Long sessionId;
    }

    @Data
    public static class ExamIdDTO {
        @NotNull(message = "试卷ID不能为空")
        private Long examId;
    }
    
    @Data
    public static class ExamStudentDTO {
        @NotNull(message = "试卷ID不能为空")
        private Long examId;
        @NotNull(message = "学生ID不能为空")
        private Long studentId;
    }
}
